package im

import (
    "fmt"
	"errors"
	//"strings"
	"reflect"
	"encoding/json"
	"dhfshop/controllers/base"
	"thirdpaysdk/api/superpay"
	"github.com/astaxie/beego"
	"dhfshop/domain/im"
	"dhfshop/domain/pay"
	"dhfshop/service/redisgo"
)

type SuperPayNotifyController struct {
	base.BaseController
}

//superpay异步回调
func (this *SuperPayNotifyController) SuperPayNotify() {
	notifyData := this.Ctx.Input.RequestBody
	beego.Debug("SuperPayNotify notifyData:", string(notifyData))
	//
	var response superpay.SuperPayMsg
	this.ParseForm(&response)
	//
	//beego.Debug("SuperPayNotify OuterTradeNo:", response.OuterTradeNo)
    //beego.Debug("SuperPayNotify TradeAmount:", response.TradeAmount)
	//
	var payInfoCache *paylayer.PayInfoCache = new(paylayer.PayInfoCache)
	cacheKey := "payorder_" + response.OuterTradeNo
	redisconn := redisgo.GetInstance()
	if cacheValue, err := redisconn.GetString(cacheKey); err == nil && len(cacheValue) > 5  {
	    //beego.Debug("cache pay info:", cacheValue)
		if err = json.Unmarshal([]byte(cacheValue), payInfoCache); err == nil {
			
		}
	}else{
	    beego.Debug("cache pay info err:", err.Error())
		return 
	}
	rspMap, err := superpay.SuperpayNotify(&response, payInfoCache.MchId, payInfoCache.AppKey)
	if err != nil {
	    beego.Debug("SuperPayNotify:", err.Error())
		return
	}
	reqMap := make(map[string]string)
	for key, value := range rspMap {
		switch value.(type) {
			case string:
			   reqMap[key] = value.(string)
			case int:
			   reqMap[key] = fmt.Sprintf("%d", value.(int))
			case int32:
			   reqMap[key] = fmt.Sprintf("%d", value.(int32))
            case int64:
			   reqMap[key] = fmt.Sprintf("%d", value.(int64))
			case float32:
			   reqMap[key] = fmt.Sprintf("%f", value.(float32))
			case float64:
			   reqMap[key] = fmt.Sprintf("%f", value.(float64))
			default:
				err = errors.New("value type is not supported: value=" + reflect.ValueOf(value).Kind().String())
				beego.Debug("RoyalPayNotify:", err.Error())
		}
	}
	reqMap["LocalKind"] = "SUPER_PAY_NOTIFY"
	reqMap["attach"] = payInfoCache.OrderKind
	reqMap["currency"] = payInfoCache.Currency
	imlayer.PushMsgSvrIns.PushDao <- &reqMap
	this.Ctx.WriteString("success")
	return
}
